﻿using System;
using System.IO;
using System.Linq;

namespace Pvf.Core
{
    /// <summary>
    /// 转换器基类
    /// </summary>
    public abstract class PvfConverterBase : IPvfConverter
    {
        public IPvfObjectLayout Layout { get; private set; }

        public void Init(IPvfObjectLayout layout)
        {
            Layout = layout;

            OnInit();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        protected virtual void OnInit()
        {

        }

        /// <summary>
        /// 类型检测
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="types"></param>
        protected void TypeCheck(BinaryReader reader, params int[] types)
        {
            var type = reader.ReadByte();

            if (!types.Any(x => x == type))
            {
                var placement = reader.ReadUInt32();

                throw new InvalidCastException($"无效操作, 类型<{placement}::{Layout.Env.StringTable[(int)placement]}>需要[{string.Join(",", types)}],但是获取到:{type}");
            }
        }

        /// <summary>
        /// 能否反序列化?
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public virtual bool CanRead(BinaryReader reader)
        {
            return true;
        }
    }
}
